<template>
    <BasicInformation :title="title" @action="handleAction" :primary-actions="mainActions"></BasicInformation>
    <div class="add">
       <div class="common-layout">
         <el-container>
           <el-main>
             <el-row>
               <el-col :span="24">
                 <div class="grid-content ep-bg-purple">
                   <h4>基本信息</h4>
                   <el-form :inline="true" :model="salesAdvance" :rules="rules" status-icon ref="formRef">
                     <el-form-item label="单据编号" prop="docCode">
                 <el-input
                     v-model="salesAdvance.docCode"
                     style="width: 240px"
                     placeholder="请输入单据编号"
                     clearable
                     :disabled="true"
                     />
                         </el-form-item>
                     <!-- 客户 -->
                     <el-form-item label="客户" prop="cid">
                             <el-select
                               v-model="salesAdvance.cid"
                               placeholder="请选择客户"
                               style="width: 240px"
                               clearable
                               filterable
                             >
                               <el-option
                                 v-for="customer in customerList"
                                 :key="customer.id"
                                 :label="`${customer.code} - ${customer.name}`"
                                 :value="customer.id"
                               />
                             </el-select>
                           </el-form-item>

                     <!-- 报价日期 -->
                     <el-form-item label="单据日期" prop="docDate">
                       <el-date-picker
                         v-model="salesAdvance.docDate"
                         type="date"
                         placeholder="请选择日期"
                         value-format="YYYY-MM-DD"
                         :disabled-date="disabledDate"
                       />
                     </el-form-item>
                     <!-- 业务员 -->
                    <el-form-item label="业务员" prop="uuid">
                            <el-select
                              v-model="salesAdvance.uid"
                              placeholder="请选择业务员"
                              style="width: 240px"
                              clearable
                              filterable
                            >
                              <el-option
                                v-for="user in userList"
                                :key="user.id"
                                :label="user.name"
                                :value="user.id"
                              />
                            </el-select>
                          </el-form-item>
                     <!-- 部门 -->
                     <el-form-item label="部门" prop="did">
                       <el-select
                         v-model="salesAdvance.did"
                         placeholder="请选择部门"
                         style="width: 240px;"
                         clearable
                       >
                         <el-option
                           v-for="dept in deptList"
                           :key="dept.id"
                           :label="dept.name"
                           :value="dept.id"
                         />
                       </el-select>
                     </el-form-item>

                      <el-form-item label="单据备注" prop="notes">
                           <el-input v-model="salesAdvance.notes" style="width: 240px"
                             placeholder="请输入单据备注" />
                       </el-form-item>
                   </el-form>
                 </div>
               </el-col>
             </el-row>
           </el-main>
         </el-container>
       </div>
     </div>
   <!-- 收款信息表格 -->
  <div class="collection-info">
    <h4>预收款信息</h4>
    <el-table :data="paymentAccounts" border style="width: 100%">
      <el-table-column label="收款账户" align="center" width="150">
        <template #default="scope">
          <el-select
            v-model="scope.row.accountName"
            placeholder="请选择账户"
            clearable
          >
            <el-option
              v-for="account in payAccountList"
              :key="account.id"
              :label="account.account"
              :value="account.id"
            />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="预收款方式" align="center" width="150">
        <template #default="scope">
          <el-select
            v-model="scope.row.paymentMethod"
            placeholder="请选择方式"
            clearable
          >
            <el-option
              v-for="method in payIdList"
              :key="method.id"
              :label="method.payName"
              :value="method.id"
            />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="预收款金额" align="center" width="180">
        <template #default="scope">
          <el-input-number
            v-model="scope.row.amount"
            :min="0"
            :precision="2"
            controls-position="right"
            style="width: 160px"
          />
        </template>
      </el-table-column>

      <el-table-column label="手续费" align="center" width="150">
        <template #default="scope">
          <el-input-number
            v-model="scope.row.fee"
            :min="0"
            :precision="2"
            controls-position="right"
            style="width: 120px"
          />
        </template>
      </el-table-column>

      <el-table-column label="交易号/票据号" align="center">
        <template #default="scope">
          <el-input
            v-model="scope.row.transactionNo"
            placeholder="请输入交易号"
            clearable
          />
        </template>
      </el-table-column>

      <el-table-column label="收款备注" align="center">
        <template #default="scope">
          <el-input
            v-model="scope.row.notes"
            placeholder="请输入备注"
            clearable
          />
        </template>
      </el-table-column>
    </el-table>
    <div class="validation-info">
    <el-alert
      v-if="netCollectionAmount > maxSettleAmount"
      type="error"
      :closable="false"
      show-icon
    >
      超额收款！可收上限：¥{{ maxSettleAmount.toFixed(2) }}
    </el-alert>

    <div class="amount-summary">
      <span>净收款金额：¥{{ netCollectionAmount.toFixed(2) }}</span>
      <span style="margin-left: 20px">已收款金额：¥{{ totalCurrentSettle.toFixed(2) }}</span>
    </div>
  </div>

  <!-- 修改确定按钮事件处理 -->
  <el-button
    type="primary"
    @click="confirmSelection"
    :disabled="totalCurrentSettle >= maxSettleAmount"
  >
    确定（剩余可核销：¥{{ (maxSettleAmount - totalCurrentSettle).toFixed(2) }}）
  </el-button>


    <div class="total-summary">
      <div class="total-label">收款合计</div>
      <div class="total-amount">{{ formatPaymentTotal }}</div>
    </div>
  </div>

  <!-- 源单信息表格 -->
  <div class="source-info">
    <div class="toolbar">
      <el-button type="primary" @click="selectSourceOrder">选择源单</el-button>
    </div>

    <el-table :data="sourceOrders" border style="width: 100%">
      <el-table-column label="源单日期" align="center" width="120">
        <template #default="scope">{{ scope.row.orderDate }}</template>
      </el-table-column>

      <el-table-column label="源单类型" align="center" width="120">
        <template #default="scope">{{ scope.row.orderType }}</template>
      </el-table-column>

      <el-table-column label="源单编号" align="center" width="180">
        <template #default="scope">{{ scope.row.orderCode }}</template>
      </el-table-column>

      <el-table-column label="客户名称" align="center" width="150">
        <template #default="scope">{{ scope.row.customerName }}</template>
      </el-table-column>
      <el-table-column label="订单金额" align="center" width="120">
    <template #default="scope">
      ¥{{ scope.row.totalAmount.toFixed(2) }}
    </template>
  </el-table-column>

  <el-table-column label="已预收金额" align="center" width="120">
    <template #default="scope">
      ¥{{ (scope.row.settledAmount || 0).toFixed(2) }}
    </template>
  </el-table-column>

  <el-table-column label="本次预收" align="center" width="150">
    <template #default="scope">
              <el-input-number
            v-model="scope.row.currentAdvance"
            :min="0"
            :max="Math.max(scope.row.totalAmount * 0.2 - (scope.row.settledAmount || 0), 0)"
            :precision="2"
          />
      <div v-if="scope.row.currentAdvance > scope.row.totalAmount * 0.2"
         style="color: red; font-size: 12px">
      超出20%限额（限额：¥{{ (scope.row.totalAmount * 0.2).toFixed(2) }}）
    </div>
    <el-alert
  v-if="netCollectionAmount > maxSettleAmount"
  type="error"
  :closable="false"
  show-icon
>
  超额收款！可收上限：¥{{ maxSettleAmount.toFixed(2) }}（按订单金额20%计算）
</el-alert>
    </template>
  </el-table-column>


      <el-table-column label="操作" align="center" width="80">
        <template #default="scope">
          <el-button link type="danger" @click="removeSourceOrder(scope.row)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>


   <el-dialog
   v-model="dialogVisible"
   title="销售订单"
   width="80%"
   top="5vh"
 >
   <!-- 查询条件区域 -->
   <div class="dialog-header">
     <el-input
       v-model="searchForm.code"
       placeholder="请输入单据编号"
       style="width: 240px;margin-right: 15px"
     />
     <span class="date-label">单据日期：</span>
     <el-date-picker
       v-model="searchForm.startDate"
       type="date"
       placeholder="开始日期"
       value-format="YYYY-MM-DD"
       style="width: 160px"
     />
     <span class="date-separator">~</span>
     <el-date-picker
       v-model="searchForm.endDate"
       type="date"
       placeholder="结束日期"
       value-format="YYYY-MM-DD"
       style="width: 160px;margin-right: 15px"
     />
     <el-button type="primary" icon="Search" @click="searchsalesOrderList">查询</el-button>
     <el-button icon="Refresh" @click="resetSearch">重置</el-button>
     <el-button icon="ArrowDown">展开</el-button>
   </div>

   <!-- 选择状态提示 -->
   <div class="selected-info">
     <span>已选择{{ selectedCount }}项</span>
     <el-button link type="primary" @click="clearSelection">清空</el-button>
   </div>

   <!-- 表格区域 -->
   <el-table
     :data="salesOrderList"
     border
     height="60vh"
     @selection-change="handleSelectionChange"

   >
     <el-table-column type="selection" width="55" align="center" />
     <el-table-column prop="docCode" label="单据编号" width="180" />
     <el-table-column prop="docDate" label="单据日期" width="120" />
     <el-table-column prop="notes" label="单据备注" width="200" />
     <el-table-column prop="cidStr" label="客户" width="120" />
     <el-table-column prop="didStr" label="业务部门" width="120" />
     <el-table-column prop="uidStr" label="业务员" width="120" />
     <el-table-column prop="closed" label="已关闭" width="100" align="center">
       <template #default="scope">
      <el-tag :type="scope.row.status === 11 ? 'danger' : 'success'" size="small">
        {{ scope.row.status === 11 ? '是' : '否' }}
      </el-tag>
    </template>
     </el-table-column>
   </el-table>

   <!-- 分页及操作按钮 -->
   <div class="dialog-footer">
      <!-- 分页组件 -->
      <div class="pagination-wrapper">
             <el-pagination
                 background
                 layout="prev, pager, next"
                 :total="totalItems"
                 :page-size="PopupsPageSize"
                 :current-page="PopupsPageNo"
                 @current-change="handlePageChange"
             />
         </div>
     <div class="action-buttons">
       <el-button @click="dialogVisible = false">关闭</el-button>
       <el-button type="primary" @click="confirmSelection">确定</el-button>
     </div>
   </div>
 </el-dialog>



 </template>


 <script setup lang="ts">
 import { ref, reactive,withKeys ,watch,computed, onMounted} from 'vue';
 import BasicInformation from '@/public-view/BasicInformation.vue';
 import type {ComponentSize, FormInstance, FormRules} from 'element-plus'
 import {ElInput, ElAutoResizer, ElTableV2} from 'element-plus'
 import type {FunctionalComponent} from 'vue'
 import type {Column, InputInstance} from 'element-plus'
 import { useRouter,useRoute } from 'vue-router';
 import type { Customer } from '@/types/public-xs/Customer';
 import axios from 'axios';
 import { ElMessageBox, ElMessage } from 'element-plus'
 import type { SalesCollection,SalesCollectionRefunddetail,SalesAdvance,SalesAdvanceDetail,SalesOrder,SalesOrderDetail} from '@/types/public-xs/salesDocuments';
 import type { User,Department } from '@/types/rs/User';
 import type {PaymentMethod,CwOtherIncomePayname}  from '@/types/public-xs/CwOtherIncome'
 import SalesAdvanceInfo from './SalesAdvanceInfo.vue';
 import request from '@/util/request'
import type { PayAccount } from '@/types/cw/Public';
 let docCode=ref('')
 let sourceSheet=ref('')
 let title=ref('预收单')
 let pageNo=ref(1)
 let pageSize=ref(5)
 let allPage=ref(0)
 let router=useRouter()

 let salesAdvanceDetailList=ref<SalesAdvanceDetail[]>([])
 //销售预收单对象
 let salesAdvance=ref<SalesAdvance>({
    id: 0,
    docCode: '',
    docDate:new Date,
    cid:  null,
    uid: null,
    advanceAmount: 0,
    status: 0,
    notes: '',
    createBy: '毕建峰',
    createTime: new Date,
    updateBy: '毕建峰',
    updateTime:new Date,
    isDelete: 0,
    settledAmount: 0,
    unsettledAmount: 0,
    sourceSheet: 'string',
    typeId: 32,
    did: null,
    uidStr: '',
    didStr: '',
    cidStr: '',
    details:salesAdvanceDetailList.value,
 })



 //商品查询条件
 const queryConditions = reactive({
   combine: '',
   kid: ''
 })
 const rules = reactive({
   cid: [{ required: true, message: '请输入选择结算用户', trigger: 'blur' ,type:'number'}],
   docCode: [{ required: true, message: '请选择订单日期', trigger: 'change' }],
   bjName: [{ required: true, message: '请输入订单名称', trigger: 'blur' }],
   uid: [{ required: true, message: '请输入业务员ID', trigger: 'blur' }],
   did: [{ required: true, message: '请选择部门', trigger: 'change' }]
 })
 const disabledDate = (time: Date) => {
     return time.getTime() > Date.now()
 }
 // 修改handleAction方法
 const handleAction = (action:string) => {
   switch(action) {
     case 'choose':
       if (!salesAdvance.value.cid) {
         ElMessage.warning('请先选择客户')
         return
       }
       dialogVisible.value = true
        // 自动触发数据加载
        searchsalesOrderList()
       break
     case 'save-add':
     insertSalesClo()
       break;
     case 'history':
       router.push('/home/salesAdvanceInfo')
       break;



   }
 }

 const mainActions = ref([
   {
     name: 'save',
     label: '保存',
     type: 'primary',
     icon: 'DocumentAdd'
   },
   {
     name: 'save-add',
     label: '保存新增',
     disabled: false
   },
   {
     name: 'audit',
     label: '审核',
     hidden: false
   },
   {
     name: 'choose',
     label: '选择源单',
     hidden: false
   },
   {
     name: 'history',
     label: '历史单据',
     badge: 3 // 角标数字
   }
 ])



 //访问方法并获取单据编号
 let getDocCode=async()=>{
   let response=await request.post('/xs/counter/addCode',{docType:'XSYSD'})
   docCode.value=response.data.data
   salesAdvance.value.docCode=docCode.value
 }

 onMounted(async () => {
   await getDocCode()
 })

 // todo
 const generateUUID = () => {
     return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
     const r = (Math.random() * 16) | 0
     const v = c === 'x' ? r : (r & 0x3) | 0x8
     return v.toString(16)
   })
 }
 //动态加载客户
let customerList = ref<Customer[]>([])
let selectCustomer = async () => {
    let response = await request.post('/basic/Customer/selectAllCustomer')
    customerList.value = response.data.data
    console.log(customerList.value)

}
selectCustomer()

//查询业务员的方法
let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await request.post('/per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

let deptList=ref<Department[]>([])
let selectDept=async()=>{
  let response=await request.post('/per/dept/getAll')
  deptList.value=response.data.data
  console.log(deptList.value)
}
selectDept()

 //获取到付款方式的方法
 let payIdList=ref<PaymentMethod[]>([])
 let selectpayId=async()=>{
  let response=await request.post("/cw/PaymentMethodController/selectPaymentMethod")
   payIdList.value=response.data.data
   console.log(payIdList.value)
 }
selectpayId()
 //获取收款名字的方法
 let payeeNameList=ref<CwOtherIncomePayname[]>([])
 let selectpayeeNameList=async()=>{
   let response= await request.post("/cw/PaymentMethodController/selectCwOtherIncomePayname")
   payeeNameList.value=response.data.data
 }
selectpayeeNameList()
 const tableData = ref([{
   id: generateUUID(),
   goodId:0,
   code: '',
   name:'',
   quantity: 1,
   actualPrice: 0,
   returnReason: '',
   tax: 13,
   taxIncludedPrice: 0,
   stock:100,
   unit: '件',
   kname:'测试',
   returnQuantity:0
 }])


 const newSelectedRows = ref<any[]>([])

 // 处理选中行变化
 const newHHandleSelectionChange = (selection: any[]) => {
   newSelectedRows.value = selection
 }

 // 删除选中行方法（添加确认对话框）
 const deleteSelectedRows = async () => {
   if (newSelectedRows.value.length === 0) {
     ElMessage.warning('请先选择要删除的行')
     return
   }

   try {
     await ElMessageBox.confirm(
       `确定要删除选中的 ${newSelectedRows.value.length} 行吗？`,
       '删除确认',
       {
         confirmButtonText: '确定',
         cancelButtonText: '取消',
         type: 'warning'
       }
     )
     // 通过ID过滤实现删除
     const selectedIds = new Set(newSelectedRows.value.map(row => row.id))
     tableData.value = tableData.value.filter(row => !selectedIds.has(row.id))
     ElMessage.success('删除成功')
   } catch (error) {
     ElMessage.info('已取消删除')
   }
 }

 let payAccountList = ref<PayAccount[]>([])
let  selectAllBankAccount=async()=>{
  let accountRes = await request.post("basic/Account/selectAllAccount")
  payAccountList.value = accountRes.data.data
}
selectAllBankAccount()

 //价格校验
 const validatePrice = (row:any) => {
   row.actualPrice = row.actualPrice.replace(/[^\d.]/g, '')
 }

 // 含税价计算
 const calculateTaxPrice = (row:any) => {
   if (row.actualPrice && row.vatRate) {
     row.taxIncludedPrice = (row.actualPrice * (1 + row.vatRate/100)).toFixed(2)
   }
 }

 //格式化金额显示
 const totalAmount = computed(() => {
   return tableData.value.reduce((sum, row) => {
     const price = Number(row.actualPrice) || 0
     const qty = Number(row.returnQuantity) || 0 // 关键修改点
     return sum + (price * qty)
   }, 0)
 })
 const formatTotal = computed(() => {
   return `¥${totalAmount.value.toFixed(2)}`
 })
 let PopupsPageNo=ref(1)
 let PopupsPageSize=ref(10)
 const selectedCount = ref(0)
 const totalItems = ref(0)
 const dialogVisible = ref(false)
 const currentSelected =ref<SalesOrder|null>()
 const selectedRows =ref<SalesOrder[]>([])
 const searchForm = reactive({
     code: '',
   startDate: '',
   endDate: ''
 })
 // 表格选择处理
 const handleSelectionChange = (selection:any) => {
   selectedRows.value = selection
   selectedCount.value = selection.length
   if (selection.length > 0) {
     currentSelected.value = selection[0]
   } else {
     currentSelected.value = null
   }
 }
 const clearSelection = () => {

 }

 //分页方法
 let handlePageChange=()=>{

 }
 let salesOrderList=ref<SalesOrder[]>([])
 // 获取源单数据
 const searchsalesOrderList = async () => {
   try {
     const params = {
       code: searchForm.code,
       startDate: searchForm.startDate,
       endDate: searchForm.endDate,
       pageNo: PopupsPageNo.value,
       pageSize: PopupsPageSize.value,
       cid:salesAdvance.value.cid
     }
     const res = await request.post('/xs/salesOrder/selectSalesOrderByPage', params)
     salesOrderList.value = res.data.data.list
     totalItems.value = res.data.data.total
   } catch (error) {
     console.error('查询失败:', error)
   }
 }
 const resetSearch = () => {
   searchForm.code = ''
   searchForm.startDate = ''
   searchForm.endDate = ''
   searchsalesOrderList()
 }

 const confirmSelection = async() => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条源单单')
    return
  }
 
  const newSourceOrders = selectedRows.value.map(row => ({
  orderId: row.id,
  orderDate: row.createTime,
  orderType: '销售订单', // 根据类型值转换文本
  orderCode: row.docCode,
  customerName: customerList.value.find(c => c.id === row.cid)?.name,
  totalAmount: row.totalAmount,       // 使用totalAmount
  settledAmount:row.arBalance,   // 已预收金额
  currentAdvance: 0
}));
  const docCode = currentSelected.value?.docCode ?? '未选择源单'
  salesAdvance.value.sourceSheet=docCode
  const existingIds = new Set(sourceOrders.value.map(o => o.orderId))
  const validOrders = newSourceOrders.filter(o => !existingIds.has(o.orderId))

  // 添加新订单
  sourceOrders.value = [...sourceOrders.value, ...validOrders]
  
  // 关闭对话框并重置选择
  dialogVisible.value = false
  selectedRows.value = []
  selectedCount.value = 0
  ElMessage.success(`成功添加${validOrders.length}条源单`)

 }

 const generateDetails = () => {
  return paymentAccounts.value.map(payment  => ({
    id: 0,
    mainCode: salesAdvance.value.docCode,
    advanceType: Number(payment.paymentMethod),
    advanceName: paymentMethods.value.find(m => m.value === Number(payment.paymentMethod))?.value,
    bankAccount: payment.accountName,
    amount: payment.amount,
    createBy: '毕建峰',
    createTime: new Date,
    updateBy: '毕建峰',
    updateTime:new Date,
    isDelete: 0,
    fee:payment.fee,
    notes:payment.notes
  })) as []
};

 const paymentAccounts = ref([
  {
    id: 1,
    accountName: 0,
    paymentMethod: 0,
    amount: 0,
    fee: 0,
    transactionNo: '',
    notes:'',//单据备注

  }
])

const bankAccounts = ref([
  { value: 1, label: '招商银行（尾号8899）' },
  { value: 2, label: '工商银行（尾号5566）' }
])

const paymentMethods = ref([
  { value: 1, label: '银行转账' },
  { value: 2, label: '支付宝' },
  { value: 3, label: '微信支付' }
])

// 新增源单信息相关数据
const sourceOrders = ref<any[]>([])
const sourceDialogVisible = ref(false)

// 计算属性
const formatPaymentTotal = computed(() => {
  const total = paymentAccounts.value.reduce(
    (sum, row) => sum + Number(row.amount) - Number(row.fee),
    0
  )
  return `¥${total.toFixed(2)}`
})

// 新增方法
const selectSourceOrder = () => {
  sourceDialogVisible.value = true

}



watch(paymentAccounts, (newVal) => {
  const totalAdvance = newVal.reduce((sum, row) => sum + (row.amount || 0), 0);
  sourceOrders.value.forEach(order => {
    order.currentAdvance = Math.min(order.totalAmount * 0.2, totalAdvance);
  });
}, { deep: true });


// 可收上限计算（按每个订单20%计算）
const maxSettleAmount = computed(() => {
  return sourceOrders.value.reduce((sum, order) => {
    // 计算每个订单最大可预收金额（订单金额20% - 已核销金额）
    const maxPerOrder = order.totalAmount * 0.2 - (order.settledAmount || 0)
    return sum + Math.max(maxPerOrder, 0) // 防止负数
  }, 0)
})

// 净收款金额计算
const netCollectionAmount = computed(() => {
  return paymentAccounts.value.reduce((sum, row) =>
    sum + (Number(row.amount) || 0) - (Number(row.fee) || 0), 0);
});



const removeSourceOrder = (row: any) => {
  sourceOrders.value = sourceOrders.value.filter(item => item.orderId !== row.orderId)
}

const totalSettledAmount = computed(() => {
  return sourceOrders.value.reduce((sum, order) =>
    sum + (order.currentSettle || 0), 0)
});

// 监听器更新主单收款金额
watch(totalSettledAmount, (newVal) => {
    salesAdvance.value.advanceAmount = newVal;
});
const validateSettlement = () => {
  const validPayments = paymentAccounts.value.every(p =>
    p.accountName && p.paymentMethod && p.amount > 0
  );

  // 类型匹配校验
  const validTypes = paymentAccounts.value.every(p =>
    [1, 2, 3].includes(p.paymentMethod)
  );

  if (!validPayments || !validTypes) {
    ElMessage.error('收款信息填写不完整或类型错误');
    return false;
  }
  return true;
};



// 计算当前核销总金额
const totalCurrentSettle = computed(() => {
  return sourceOrders.value.reduce((sum, order) =>
    sum + (Number(order.currentSettle) || 0)
  , 0)
})



 //点击新增后新增收款单
 let insertSalesClo =async()=>{
  if (!validateSettlement()) {
    ElMessage.error('存在非法核销金额，请检查源单可核销额度');
    return;
  }

  // 构造明细数据
  const details = generateDetails()
  salesAdvance.value.advanceAmount = totalSettledAmount.value;
  salesAdvance.value.settledAmount = totalSettledAmount.value;
  salesAdvance.value.advanceAmount = paymentAccounts.value.reduce(
  (sum, row) => sum + row.amount - row.fee, 0
);
  // 更新主单收款总额
    let response=await request.post("/cw/SalesAdvanceController/insertSalesAdvance",{
        salesAdvance:salesAdvance.value,
        details:details
    })
    if(response.data.code=='200'){
      ElMessage.success("新增成功")
      router.push("/home/salesAdvanceInfo")
    }else{
      ElMessage.error("新增失败")
    }
 }

 </script>


 <style scoped>
 .el-row {
     margin-bottom: 20px;
 }

 .el-row:last-child {
     margin-bottom: 0;
 }

 .el-col {
     border-radius: 4px;
 }

 .grid-content {
     border-radius: 4px;
     min-height: 36px;
 }
 .required-label::after {
   content: "*";
   color: #f56c6c;
   margin-left: 4px;
 }

 .goods-table {
   margin-top: 20px;
 }

 .toolbar {
   margin-bottom: 15px;
   padding: 10px;
   background: #f5f7fa;
   border-radius: 4px;
 }

 .el-table :deep(.el-input__inner) {
   text-align: center;
 }
 .total-summary {
   background: #fff8dc; /* 浅黄色背景 */
   padding: 12px 20px;
   display: flex;
   justify-content: flex-end;
   border: 1px solid #ebeef5;
   border-top: none;
 }

 .total-label {
   font-weight: 600;
   color: #606266;
   margin-right: 30px;
 }

 .total-amount {
   color: #f56c6c;
   min-width: 120px;
   text-align: right;
   font-family: Arial, sans-serif;
 }
 .pagination-wrapper {
     margin-top: 16px;
     display: flex;
     justify-content: flex-end;
 }
 .dialog-header {
   display: flex;
   align-items: center;
   margin-bottom: 15px;
   flex-wrap: wrap;
   gap: 10px;
 }

 .date-label {
   color: #606266;
   margin: 0 10px;
 }

 .date-separator {
   margin: 0 8px;
   color: #c0c4cc;
 }

 .selected-info {
   margin: 12px 0;
   display: flex;
   align-items: center;
   gap: 10px;
   color: #606266;
 }

 .dialog-footer {
   display: flex;
   justify-content: space-between;
   align-items: center;
   margin-top: 15px;
 }

 .pagination-info {
   color: #606266;
 }

 .action-buttons {
   display: flex;
   gap: 15px;
 }

 :deep(.el-dialog__header) {
   border-bottom: 1px solid #ebeef5;
 }

 .collection-info {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.source-info {
  margin-top: 20px;
  border-top: 2px solid #ebeef5;
  padding-top: 15px;
}

.toolbar {
  margin-bottom: 15px;
}

.total-summary {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 15px;
  padding: 10px;
  background: #f4f4f5;
  border-radius: 4px;
}

.total-label {
  font-weight: 600;
  margin-right: 20px;
}

.total-amount {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
}
.validation-info {
  margin: 15px 0;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
}

.amount-summary {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

.el-alert {
  margin-bottom: 10px;
}
 </style>







